package com.ivo.quartz;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ivo.biz.Performance;
import com.ivo.biz.PerformanceManager;
import com.ivo.biz.PerformanceMon;
import com.ivo.biz.PerformanceService;
import com.ivo.biz.Rule;
import com.ivo.biz.RuleService;

/**
 * 
 *
 * @author Minkey Wang
 * @version 2017年7月24日
 */
@Repository
public class CellPerformanceQuartz {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private PerformanceService performanceService;
    
    @Autowired
    private PerformanceManager performanceManager;
    
    @Autowired 
    private RuleService ruleService;
    
    
	@Transactional
	@Scheduled(cron = "0 0 7 16 * ? ")//每月16日上午07:00触发
	public void execute() {
		SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance(); 
		
		String str = sdf.format(calendar.getTime());
		String month = str.substring(0, 7);
//		String month ="2017-09";
				
		calendar.add(Calendar.MONTH, -1);    //得到前一个月   
		String str1 = sdf.format(calendar.getTime());
		String month1 = str1.substring(0, 7);
//		String month1 = "2017-06";
		
		List<PerformanceMon> list = performanceService.listByMon(month);
		for(PerformanceMon objPerformanceMon:list){
			String emp_id = objPerformanceMon.getEmp_id();
			Performance objPerformanceExist = performanceService.getPerformance(month,emp_id);
			if(objPerformanceExist==null){
				Performance objPerformance =new Performance();
				objPerformance.setMonth(month);
				objPerformance.setFactory(objPerformanceMon.getFactory());
				objPerformance.setEmp_id(objPerformanceMon.getEmp_id());
				objPerformance.setEmp_name(objPerformanceMon.getEmp_name());
				objPerformance.setGender(objPerformanceMon.getGender());
				objPerformance.setOpe_fk(objPerformanceMon.getOpe_fk());
				objPerformance.setClassType(objPerformanceMon.getClassType());
				
				logger.info("考勤得分计算start"+emp_id);
				Double shfthour = objPerformanceMon.getShftHour();
				Double attdhour = objPerformanceMon.getAttdHour();
				BigDecimal shfthour1 = new BigDecimal(shfthour);
				BigDecimal attdhour1 = new BigDecimal(attdhour);
				BigDecimal diffhour = shfthour1.subtract(attdhour1);//差异时数=应出勤-实际出勤
				int i = diffhour.compareTo(BigDecimal.ZERO);  //i = 差异时数-0
				Double attendance=0.0;
				if(i<0){ //超勤 
					Double s= diffhour.divide(new BigDecimal(10), 0,BigDecimal.ROUND_HALF_UP).doubleValue();
					attendance = 10.0 + Math.abs(s);
				}
				else if (i>0){ //缺勤
					Double s= diffhour.divide(new BigDecimal(8), 0,BigDecimal.ROUND_HALF_UP).doubleValue();
					attendance = 10.0 - Math.abs(s);
					
				}
				else if (i==0){//满勤
					attendance = 10.0;
				}
				if(attendance>15) attendance=15.0;
				if(attendance<0)  attendance=0.0;
				objPerformance.setAttendance(attendance);
//				System.out.println("shfthour:"+shfthour+" attdhour："+attdhour+" attendance:"+attendance);				
				logger.info("考勤得分计算end"+emp_id);
				
				logger.info("工作纪律和配合度得分计算start"+emp_id);
				objPerformance.setDiscipline(objPerformanceMon.getDiscipline());
				objPerformance.setCompatibility(objPerformanceMon.getCompatibility());
				logger.info("工作纪律和配合度得分计算end"+emp_id);
				
				logger.info("专业技能得分计算start"+emp_id);
				Double specialty = 0.0;
				if(objPerformanceMon.getLevel()!=null && objPerformanceMon.getLevel().contains("Level")){
					specialty = 8.0;
				}
				if(objPerformanceMon.getCount()!=null && objPerformanceMon.getCount()>0){
					specialty = specialty+2;
				}
				if(specialty>10) specialty=10.0;
				objPerformance.setSpecialty(specialty);
				logger.info("专业技能得分计算end"+emp_id);
				
				objPerformance.setOperation(25.0);
				objPerformance.setAudit(10.0);
				performanceManager.save(objPerformance);
				
			}
			else {
				objPerformanceExist.setFactory(objPerformanceMon.getFactory());
				objPerformanceExist.setEmp_name(objPerformanceMon.getEmp_name());
				objPerformanceExist.setGender(objPerformanceMon.getGender());
				objPerformanceExist.setOpe_fk(objPerformanceMon.getOpe_fk());
				objPerformanceExist.setClassType(objPerformanceMon.getClassType());
				
				logger.info("考勤得分计算start"+emp_id);
				Double shfthour = objPerformanceMon.getShftHour();
				Double attdhour = objPerformanceMon.getAttdHour();
				BigDecimal shfthour1 = new BigDecimal(shfthour);
				BigDecimal attdhour1 = new BigDecimal(attdhour);
				BigDecimal diffhour = shfthour1.subtract(attdhour1);//差异时数=应出勤-实际出勤
				int i = diffhour.compareTo(BigDecimal.ZERO);  //i = 差异时数-0
				Double attendance=0.0;
				if(i<0){ //超勤 
					Double s= diffhour.divide(new BigDecimal(10), 0,BigDecimal.ROUND_HALF_UP).doubleValue();
					attendance = 10.0 + Math.abs(s);
				}
				else if (i>0){ //缺勤
					Double s= diffhour.divide(new BigDecimal(8), 0,BigDecimal.ROUND_HALF_UP).doubleValue();
					attendance = 10.0 - Math.abs(s);
					
				}
				else if (i==0){//满勤
					attendance = 10.0;
				}
				if(attendance>15) attendance=15.0;
				if(attendance<0)  attendance=0.0;
				objPerformanceExist.setAttendance(attendance);
//				System.out.println("shfthour:"+shfthour+" attdhour："+attdhour+" attendance:"+attendance);				
				logger.info("考勤得分计算end"+emp_id);
				
				logger.info("工作纪律和配合度得分计算start"+emp_id);
				objPerformanceExist.setDiscipline(objPerformanceMon.getDiscipline());
				objPerformanceExist.setCompatibility(objPerformanceMon.getCompatibility());
				logger.info("工作纪律和配合度得分计算end"+emp_id);

				
				logger.info("专业技能得分计算start"+emp_id);
				Double specialty = 0.0;
				if(objPerformanceMon.getLevel()!=null && objPerformanceMon.getLevel().contains("Level")){
					specialty = 8.0;
				}
				if(objPerformanceMon.getCount()!=null && objPerformanceMon.getCount()>0){
					specialty = specialty+2;
				}
				if(specialty>10) specialty=10.0;
				objPerformanceExist.setSpecialty(specialty);
				logger.info("专业技能得分计算end"+emp_id);
				
				
				objPerformanceExist.setOperation(25.0);
				objPerformanceExist.setAudit(10.0);
				performanceManager.save(objPerformanceExist);
			}
		}
		
		//同步操作品质&稽核数据 ， 日期从上月的16号（包含16号）到当月的15号（包含15号）
		logger.info("操作品质&稽核数据得分计算start");
		String fromDate =month1+"-16";
		String toDate =month+"-16";
//		String fromDate ="2017-07-02";
//		String toDate = "2017-07-10";
		try {
			//获取操作品质数据
			List<Map> opelist = performanceService.getOperation(fromDate,toDate);
			for(Map obj:opelist){
				 String category = (String) obj.get("category");
				 String emp_id = (String) obj.get("emp_id");
				 Long ope_fk = (Long) obj.get("ope_fk");
				 Long type = (Long) obj.get("type");
				 Long c = (Long) obj.get("count");
				 
				 Performance objPerformance = performanceService.getPerformance(month, emp_id,ope_fk);
				 if(objPerformance!=null){
						 Double operation = objPerformance.getOperation();
						 if(operation==null) operation=25.0; //满分25
						 //异常事件：每发生一件扣2分扣满为止，不倒扣分
						 if(operation>1 && type==2){
							 operation = operation-c*2;
							 
						 }
						 //Leakage:发生一件扣5分， 取消（超出倒扣分每件2分）
						 if(type==3){
							 if(operation>4)
								 operation=operation-c*5;
//							 else {
//								 operation=operation-c*2;
//							 }
						 }
						 //MO:发生一件扣10分，取消（超出倒扣分每件5份）
						 if(type==3){
							 if(operation>9)
								 operation=operation-c*10;
//							 else {
//								 operation=operation-c*5;
//							 }
						 }
						 objPerformance.setOperation(operation); 
					 performanceManager.save(objPerformance);
				 }
				 
			}
			
			//获取稽核数据
			String fromDate1 =month1+"-10";
			String toDate1 =month+"-11";
			List<Map> opelist1 = performanceService.getOperation1(fromDate1,toDate1);
			for(Map obj:opelist1){
				 String category = (String) obj.get("category");
				 String emp_id = (String) obj.get("emp_id");
				 Long ope_fk = (Long) obj.get("ope_fk");
				 Long type = (Long) obj.get("type");
				 Long c = (Long) obj.get("count");
				 
				 Performance objPerformance = performanceService.getPerformance(month, emp_id,ope_fk);
				 if(objPerformance!=null){
						 Double audit = objPerformance.getAudit();
						 if(audit==null) audit=10.0; //满分10
						 //IPQC稽核 :发生1件扣2分，超出不倒扣分
						 if( type==22 && audit>1.9){
							 audit = audit-c*2;
							 
						 }
						//内部稽核 :发生1件扣1分，超出不倒扣分
						 if(type==23 && audit>0.9){
							audit=audit-c*1;
						 }
						 objPerformance.setAudit(audit); 
					 
					 performanceManager.save(objPerformance);
				 }
				 
			}
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("操作品质&稽核数据得分计算end");
		
		
		logger.info("cell总得分计算start");
		List<Performance> plist = performanceService.list(month);
		for(Performance objPerformance:plist){
			Double attendance = objPerformance.getAttendance();
			if(attendance==null) attendance= 0.0;
			Double operation = objPerformance.getOperation();
			if(operation==null) operation= 0.0;
			Double specialty =  objPerformance.getSpecialty();
			if(specialty==null) specialty= 0.0;
			Double audit =  objPerformance.getAudit();
			if(audit==null) audit= 0.0;
			Double discipline = objPerformance.getDiscipline();
			if(discipline==null) discipline= 0.0;
			Double compatibility = objPerformance.getCompatibility();
			if(compatibility==null) compatibility= 0.0;
			
			Double score = attendance+operation+specialty+audit+discipline+compatibility;
			objPerformance.setScore(score);
			
			Rule r = ruleService.getRule(score);
			Double bonus=0.0;
			if(r!=null) bonus = r.getBonus();
			objPerformance.setBonus(bonus);
			performanceManager.save(objPerformance);
		}
		logger.info("cell总得分计算end");
	}
}
